/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function($, owner) {
	owner.serverURI = "http://app.aquaexcel.cn:8000";
	//owner.serverURI = "http://192.168.199.206:8000";
	//owner.serverURI = "http://192.168.199.223:8000";

	owner.WarnConfigType = {
		0: "等于(=)",
		1: "不等于(=)",
		2: "大于(&gt;)",
		3: "小于(&lt;)",
		4: "大于等于(&gt;=)",
		5: "小于等于( &lt;=)",
		6: "包含字段(Like " % ")",
		7: "以**开头",
		8: "以**结尾",
		9: "正则表达式"
	};

	owner.WarnConfigTypeEN = {
		"EQUAL": 0,
		"NOT_EQUAL": 1,
		"GREATER_THAN": 2,
		"LESS_THAN": 3,
		"GREATER_THAN_OR_EQUAL": 4,
		"LESS_THAN_OR_QUAL": 6,
		"LIKE": 7,
		"BEGIN_WITH": 8,
		"END_WITH": 9,
		"REGEX": 10
	};

	owner.WarnConfigTypeEnStr = {
		"EQUAL": "等于(=)",
		"NOT_EQUAL": "不等于(=)",
		"GREATER_THAN": "大于(&gt;)",
		"LESS_THAN": "小于(&lt;)",
		"GREATER_THAN_OR_EQUAL": "大于等于(&gt;=)",
		"LESS_THAN_OR_QUAL": "小于等于( &lt;=)",
		"LIKE": "包含字段(Like " % ")",
		"BEGIN_WITH": "以**开头",
		"END_WITH": "以**结尾",
		"REGEX": "正则表达式"
	};

	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
		var settingsText = plus.storage.getItem('$settings') || "{}";
		var settings = JSON.parse(settingsText);
		//TODO 这里去设置我自己配置的信息，哈哈
		settings.autoLogin = true;
		return settings;
	};
	
	owner.getLanguage=function(){
		var lt="";
		if(!(plus.os.language=="zh_CN" || plus.os.language=="zh_Hans_CN")){
			lt="en";
		}else{
			lt="zh";
		}
		var language=plus.storage.getItem("$language") || lt;
		return language;
	}
	
	owner.setLanguage=function(language){
		plus.storage.setItem("$language",language);
	}
	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo, callback) {
		callback = callback || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.account = loginInfo.account || '';
		loginInfo.password = loginInfo.password || '';
		owner.setTempUserName(loginInfo.account);
		if(loginInfo.account.length < 5) {
			return callback('账号最短为 5 个字符');
		}
		if(loginInfo.password.length < 6) {
			return callback('密码最短为 6 个字符');
		}
		var users = JSON.parse(plus.storage.getItem('$users') || '[]');

		console.log(JSON.stringify(loginInfo));

		mui.ajax(owner.serverURI + '/m/login', {
			data: {
				username: loginInfo.account,
				password: loginInfo.password
			},
			async: false,
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				console.log(JSON.stringify(data));
				if(data.returnCode == 200) {
					return owner.createState(data.userId, loginInfo.account,loginInfo.password, data.token, callback);
				} else {
					return callback(data.returnMessage);
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return callback("服务器超时未响应。");
				//console.log(type);
			}
		});
	};
	
	owner.loginByToken=function(token,callback){
		callback = callback || $.noop;
		var state = owner.getState();
		owner.setTempUserName(state.account);
		mui.ajax(owner.serverURI + '/m/login', {
			data: {
				username: state.account,
				password: state.password//,
				//token:token
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				if(data.returnCode == 200) {
					return owner.updateState(data.userId, state.account,data.token, callback);
				} else {
					
					return callback(data.returnMessage);
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return callback("服务器超时未响应。");
				//console.log(type);
			}
		});
	}

	owner.createState = function(userId, name,password, token, callback) {
		console.log("save state " + name + " token=" + token);
		var state = owner.getState();
		state.account = name;
		state.password=password;
		state.token = token;
		state.userId = userId;
		owner.setState(state);
		return callback();
	};
	
	owner.updateState = function(userId, name,token, callback) {
		console.log("save state " + name + " token=" + token);
		var state = owner.getState();
		state.token = token;
		owner.setState(state);
		return callback();
	};
	
	owner.logout = function(){
		owner.setState();
	}

	owner.tempUserName = function() {
		var tempUserName = plus.storage.getItem('$tempUserName') || "";
		return tempUserName;
	};

	owner.setTempUserName = function(TempUserName) {
		plus.storage.setItem('$tempUserName', TempUserName);
	};

	/**
	 * 新用户注册
	 **/
	owner.reg = function(regInfo, callback) {
		callback = callback || $.noop;
		regInfo = regInfo || {};
		regInfo.account = regInfo.account || '';
		regInfo.password = regInfo.password || '';
		if(regInfo.account.length < 5) {
			return callback('用户名最短需要 5 个字符');
		}
		if(regInfo.password.length < 6) {
			return callback('密码最短需要 6 个字符');
		}
		//		if(!checkEmail(regInfo.email)) {
		//			return callback('邮箱地址不合法');
		//		}

		mui.ajax(owner.serverURI + '/m/register', {
			data: {
				username: regInfo.account,
				password: regInfo.password
			},
			async: false,
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 5000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				console.log(JSON.stringify(data));
				if(data.returnCode == 200) {
					owner.setTempUserName(regInfo.account);
					return callback();
				} else {
					return callback(data.returnMessage);
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return callback("服务器超时未响应。");
				//console.log(type);
			}
		});

	};

	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		
		var stateText = plus.storage.getItem('$state') || "{}";
		if(stateText == "{}") {
			//stateText = "{\"userId\":2}"
			//TODO 测试环境
		}
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		plus.storage.setItem('$state', JSON.stringify(state)); 
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	owner.getServerConfig = function(callback) {
		var serverConfig = plus.storage.getItem('$serverconfig') || "{}";
		if(serverConfig == ("{}")) {
			serverConfig = freshServerConfig(callback);
		}
		if(serverConfig == undefined) {
			return JSON.parse("{}");
		}
		var result = JSON.parse(serverConfig);
		if(callback)
			callback(result);
		return result;
	};

	function freshServerConfig(callback) {
		mui.ajax(owner.serverURI + '/m/listserverconfig', {
			async: false,
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				owner.setServerConfig(data);
				if(callback) {
					callback(data);
				}
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	}

	/**
	 * 设置当前状态
	 **/
	owner.setServerConfig = function(serverConfig) {
		serverConfig = serverConfig || {};
		plus.storage.setItem('$serverconfig', JSON.stringify(serverConfig));
	};

	owner.getConfigCMD = function(configid) {
		var configCMD = plus.storage.getItem('$configcmd' + configid) || "{}";
		if(configCMD == ("{}")) {
			configCMD = freshConfigCMD(configid);
		}
		if(configCMD == undefined) {
			return JSON.parse("{}");
		}
		return JSON.parse(configCMD);
	}

	function freshConfigCMD(configid) {
		mui.ajax(owner.serverURI + "/m/listcmdbtn", {
			data: {
				cid: configid
			},
			async: false,
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				owner.setConfigCMD(data, configid);
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	}

	/**
	 * 设置当前状态
	 **/
	owner.setConfigCMD = function(configCMD, configid) {
		configCMD = configCMD || {};
		plus.storage.setItem('$configcmd' + configid, JSON.stringify(configCMD));
	};

	owner.getTerminal = function(configid, callback) {
		var state = owner.getState();
		var terminals = plus.storage.getItem('$terminals_' + state.userId + configid) || "{}";
		if(terminals == ("{}")) {
			terminals = freshTerminal(configid, callback);
		}
		if(terminals == undefined) {
			return JSON.parse("{}");
		}
		var result = JSON.parse(terminals);
		if(callback)
			callback(result);
		return result;
	}

	owner.freshTerminal = function() {
		freshTerminal("");
	}

	function freshTerminal(configid, callback) {
		var state = owner.getState();
		mui.ajax(owner.serverURI + "/m/listterminal", {
			data: {
				uid: state.userId,
				//cid: configid
			},
			async: false,
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				owner.setTerminal(data, configid, state.userId); //, configid);
				if(callback)
					callback(data);
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	}

	/**
	 * 设置当前状态
	 **/
	owner.setTerminal = function(terminal, confidid, userid) { //}, configid) {
		terminal = terminal || {}; //+ configid
		plus.storage.setItem('$terminals_' + userid, JSON.stringify(terminal));
	};

	owner.getRealData = function() {
		var state = owner.getState();
		mui.ajax(owner.serverURI + "/m/getrealdata", {
			data: {
				uid: state.userId
			},
			async: false,
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	};

	owner.realData = function(callback) {
		var state = owner.getState();
		mui.ajax(owner.serverURI + "/m/getrealdata", {
			data: {
				uid: state.userId
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				callback(data);
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	};

	owner.sendCMD = function(tid, cid, callback) {
		mui.ajax(owner.serverURI + "/m/cmd", {
			data: {
				id: tid,
				cmd: cid
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				if(callback) callback(data);
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	}
	owner.addTerminal = function(cid, tname, sn, callback) {
		var state = owner.getState();
		mui.ajax(owner.serverURI + "/m/addterminal", {
			data: {
				uid: state.userId,
				cid: cid,
				tname: tname,
				sn: sn
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				if(callback) callback(data);
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	}

	owner.updateTerminal = function(tid, name, sn, callback) {
		mui.ajax(owner.serverURI + "/m/updateterminal", {
			data: {
				id: tid,
				name: name,
				sn: sn
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				if(callback) callback(data);
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	}
	owner.delTerminal = function(tid, callback) {
		mui.ajax(owner.serverURI + "/m/delterminal", {
			data: {
				id: tid
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				if(callback) callback(data);
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	}

	owner.getWarnConfig = function(configid, callback) {
		var state = owner.getState();
		var warnconfigs = plus.storage.getItem('$warnconfig_' + state.userId) || "{}";
		if(warnconfigs == ("{}")) {
			warnconfigs = freshWarnConfig(configid, callback);
		}
		if(warnconfigs == undefined) {
			return JSON.parse("{}");
		}
		var result = JSON.parse(warnconfigs);
		if(callback)
			callback(result);
		return result;
	}

	owner.freshWarnConfig = function(callback) {
		freshWarnConfig("", callback);
	}

	function freshWarnConfig(configid, callback) {
		var state = owner.getState();
		//console.log(state);
		mui.ajax(owner.serverURI + "/m/listwarnconfig", {
			data: {
				uid: state.userId,
				//cid: configid
			},
			async: false,
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				owner.setWarnConfig(data, "", state.userId); //, configid);
				if(callback)
					callback(data);
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	}

	owner.addWarnConfig = function(cid, tid, name, aimfield, ruletype, rule, callback) {
		var state = owner.getState();
		mui.ajax(owner.serverURI + "/m/addwarnconfig", {
			data: {
				uid: state.userId,
				cid: cid,
				tid: tid,
				name: name,
				aimfield: aimfield,
				ruletype: ruletype,
				rule: rule
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				if(callback) callback(data);
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	}

	owner.setWarnConfig = function(warnConfig, confidid, userid) { //}, configid) {
		warnConfig = warnConfig || {}; //+ configid
		plus.storage.setItem('$warnconfig_' + userid, JSON.stringify(warnConfig));
	};

	owner.updateWarnConfig = function(wid, name, aimfield, ruletype, rule, callback) {
		//TODO API写错了，字符拼饭了，务必注意
		mui.ajax(owner.serverURI + "/m/updatewarnconfig", {
			data: {
				id: wid,
				name: name,
				aimfield: aimfield,
				ruletype: ruletype,
				rule: rule
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				if(callback) callback(data);
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	}
	owner.delWarnConfig = function(tid, callback) {
		mui.ajax(owner.serverURI + "/m/delwarnconfig", {
			data: {
				id: tid
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				if(callback) callback(data);
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	}

	owner.freshWarnInfo = function(callback) {
		freshWarnInfo("", callback);
	}

	function freshWarnInfo(configid, callback) {
		var state = owner.getState();
		//console.log(state);
		mui.ajax(owner.serverURI + "/m/getwarninfo", {
			data: {
				uid: state.userId,
				stime: "",
				etime: ""
				//cid: configid
			},
			async: false,
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			//headers:{'Content-Type':'application/json'},	              
			success: function(data) {
				//				owner.setTerminal(data); //, configid);
				if(callback)
					callback(data);
				return data;
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(type);
				return {};
				//console.log(type);
			}
		});
	}

	var checkEmail = function(email) {
		email = email || '';
		return(email.length > 3 && email.indexOf('@') > -1);
	};

	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || $.noop;
		if(!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};

	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		plus.storage.setItem('$settings', JSON.stringify(settings));
	}
}(mui, window.app = {}));
